package com.daiyang.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.daiyang.lease.common.constant.RedisConstant;
import com.daiyang.lease.common.exception.LeaseException;
import com.daiyang.lease.common.result.ResultCodeEnum;
import com.daiyang.lease.common.utils.JwtUtil;
import com.daiyang.lease.model.entity.SystemUser;
import com.daiyang.lease.model.enums.BaseStatus;
import com.daiyang.lease.web.admin.mapper.SystemUserMapper;
import com.daiyang.lease.web.admin.service.LoginService;
import com.daiyang.lease.web.admin.vo.login.CaptchaVo;
import com.daiyang.lease.web.admin.vo.login.LoginVo;
import com.daiyang.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    SystemUserMapper systemUserMapper;
    @Override
    public CaptchaVo getCaptcha() {
        try {
            SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
            specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
            String code = specCaptcha.text().toLowerCase();
            String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
            String image = specCaptcha.toBase64();
            
            logger.info("准备存储验证码到Redis，key: {}, code: {}", key, code);
            
            // 使用setIfAbsent确保原子性操作并检查返回结果
            Boolean setResult = redisTemplate.opsForValue().setIfAbsent(key, code,
                    RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
            
            if (setResult == null || !setResult) {
                logger.error("验证码存储失败，key: {}, code: {}", key, code);
                throw new LeaseException(ResultCodeEnum.REDIS_SET_ERROR);
            }
            
            logger.info("验证码成功存储到Redis，key: {}", key);
            return new CaptchaVo(image, key);
        } catch (Exception e) {
            logger.error("生成或存储验证码时发生异常: ", e);
            throw new LeaseException(ResultCodeEnum.REDIS_SET_ERROR);
        }
    }

    @Override
    public String login(LoginVo loginVo) {
        //1.判断是否输入了验证码
        if (!StringUtils.hasText(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
//2.校验验证码
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (code == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!code.equals(loginVo.getCaptchaCode().toLowerCase())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
//3.校验用户是否存在
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        if (systemUser == null) {
            throw new
                    LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
//4.校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
//5.校验用户密码
        if
        (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword())))
        {
            System.out.println(systemUser.getPassword());
            System.out.println(DigestUtils.md5Hex(loginVo.getPassword()));
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
//6.创建并返回TOKEN
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }

}
